﻿using System.Text;

namespace Worldme.YHChatSDK.Framework.Utils
{
    internal class HttpUtil
    {

        public static HttpReq Create()
        {
            return new HttpReq();
        }

    }

    internal class HttpReq
    {
        private HttpClient _httpClient = new HttpClient();
        private HttpRequestMessage httpRequestMessage = new HttpRequestMessage();
        private Dictionary<string, string> _header = new Dictionary<string, string>();


        public HttpReq Post(string url)
        {
            var uriBuilder = new UriBuilder(url);
            httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, uriBuilder.Uri);
            return this;
        }

        public HttpReq Header(string key, string value)
        {
            _header.Add(key, value);
            return this;
        }

        public HttpReq Body(string body)
        {
            var content = new StringContent(
                    body,
                    Encoding.UTF8,
                    "application/json");
            httpRequestMessage.Content = content;
            return this;
        }

        public HttpRes Execute()
        {
            try
            {
                var response = _httpClient.Send(httpRequestMessage);
                _httpClient.Dispose();
                HttpRes res = new HttpRes(response);
                return res;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }

    internal class HttpRes
    {
        private HttpResponseMessage _httpResponseMessage = new HttpResponseMessage();

        public HttpRes(HttpResponseMessage _httpResponseMessage)
        {
            this._httpResponseMessage = _httpResponseMessage;
        }



        public string Body()
        {
            return _httpResponseMessage.Content.ReadAsStringAsync().Result;
        }

    }
}
